<?php
/**
 * User:ayou chow
 * Date: 2019-11-25
 * Time: 11:00
 */

namespace app\admin\controller;


use app\common\model\GiftModel;
use app\common\model\GiftLogModel;
use app\common\model\LiveRoomCache;
use app\common\model\UserModel;
use think\facade\Cache;
use think\facade\Request;

class GiftController extends BaseController
{

    public function index()
    {
        return $this->fetch();
    }

    public function add()
    {
        return $this->fetch();
    }

    public function edit()
    {
        $id       = Request::param('id');
        $giftinfo = GiftModel::get($id);
        if (!$giftinfo) {
            return static::bulidFail('礼物信息不存在');
        }
        $giftinfo->price = $giftinfo->price == 0 ? 0 : bcdiv($giftinfo->price, '100', 2);
        $this->assign("giftinfo", $giftinfo);
        return $this->fetch();
    }

    public function signForCos()
    {
        return parent::signForCos();
    }

    public function getlist()
    {
        $title      = Request::param('title');
        $price      = Request::param('price');
        $type       = Request::param('type');
        $price_type = Request::param('price_type');

        $where = [];
        if (mb_strlen($title, 'UTF-8') > 0) {
            $where[] = ['title', 'like', "%$title%"];
        }
        if (mb_strlen($price, 'UTF-8') > 0) {
            $where[] = ['price', '=', is_numeric($price) ? ($price * 100) : 0];
        }
        if (is_numeric($type)) {
            $where[] = ['type', '=', $type];
        }
        if (is_numeric($price_type)) {
            $where[] = ['price_type', '=', $price_type];
        }

        $gifts = GiftModel::where($where)
            ->order(['sort' => 'asc', 'id' => 'asc'])
            ->select()
            ->each(function ($query) {
                $query->price = $query->price == 0 ? 0 : bcdiv($query->price, '100', 2);
            });
        if (count($gifts) > 0) {
            return self::bulidSuccess($gifts);
        }
        return self::bulidFail("未查询到相关数据");
    }

    public function add_post()
    {
        $gift = new GiftModel(Request::param());

        if ($gift->type == 1 || $gift->type == 2) {
            if (empty($gift->animation)) {
                return self::bulidFail("请上传动画");
            }
            $gift->animat_type = 2;
        } else {
            $gift->animat_type = 1;
        }

        if (($price = rtrim(trim($this->post('price', '')), '.')) && is_numeric($price)) {
            $gift->price = bcmul($price, '100', 0);
        }


        if ($gift->save()) {
            // 记录日志
            $log_content = "添加礼物配置，ID：{$gift->id}，名称：{$gift->title}";
            parent::addAdminLog($log_content);

            return self::bulidSuccess();
        }

        return self::bulidFail();
    }

    public function edit_post()
    {
        $id        = Request::param("id");
        $all_param = Request::param();

        $gift = GiftModel::get($id);
        if (!$gift) {
            return self::bulidFail("礼物信息不存在");
        }

        if ($all_param['type'] == 1 || $all_param['type'] == 2) {
            if (empty($all_param['animation'])) {
                return self::bulidFail("请上传动画");
            }
            $all_param['animat_type'] = 2;
        } else {
            $all_param['animat_type'] = 1;
        }

        if (($price = rtrim(trim($this->post('price', '')), '.')) && is_numeric($price)) {
            $all_param['price'] = bcmul($price, '100', 0);
        }


        if ($gift->save($all_param)) {
            // 记录日志
            $log_content = "修改礼物配置，ID：{$gift->id}，名称：{$gift->title}";
            parent::addAdminLog($log_content);

            return self::bulidSuccess([], "编辑成功");
        }
        return self::bulidFail();
    }

    //上架/下架
    public function del_post()
    {
        $status    = Request::param("status");
        $giftModel = GiftModel::get(Request::param("id"));

        if (!$giftModel) {
            return self::bulidFail("参数错误");
        }

        $giftModel->status = $status;

        if ($giftModel->save()) {
            // 记录日志
            $log_content = ($status == 1 ? '上架' : '下架') . "礼物配置，ID：{$giftModel->id}，名称：{$giftModel->title}";
            parent::addAdminLog($log_content);

            return self::bulidSuccess();
        }
        return self::bulidFail();
    }

    /////////////////////////////////////////     赠礼记录      ////////////////////////////////////////----

    public function sendlog()
    {
        return $this->assign(['gifts' => json_encode(array_column(GiftModel::lists(), 'title', 'id'))])->fetch();
    }

    public function getsendlist()
    {
        $where = [];

        $id        = Request::param("id");
        $send_user = Request::param("send_user");
        $anchorid  = Request::param("anchorid");
        $liveid    = Request::param('liveid');


        if ($id) {
            $where[] = ['id', '=', $id];
        }
        if ($send_user) {
            $u_where    = (is_numeric($send_user) ? "id=$send_user OR" : '') . " nick_name like '%$send_user%'";
            $search_uid = UserModel::where($u_where)->column('id');
            $where[]    = ['uid', 'IN', $search_uid];
        }
        if ($anchorid) {
            $u_where    = (is_numeric($anchorid) ? "id=$anchorid OR" : '') . " nick_name like '%$anchorid%'";
            $search_uid = UserModel::where($u_where)->column('id');
            $where[]    = ['anchorid', 'IN', $search_uid];
        }
        if ($liveid) {
            $where[] = ['liveid', '=', $liveid];
        }

        $page      = Request::param("page");
        $limit     = Request::param("limit");
        $giftSends = GiftLogModel::where($where)
            ->with(['user' => function ($query) {
                $query->field('id, nick_name');
            }, 'anchor'    => function ($query) {
                $query->field('id, nick_name');
            }])
            ->limit(($page - 1) * $limit, $limit)
            ->order("create_time", "desc")
            ->select()->each(function ($query) {
                // 礼物单价
                $query->unit_price   = bcdiv(bcdiv($query->spend, $query->count), '100', 2);
                $query->spend        = bcdiv(strval($query->spend), '100', 2);
                $query->actual_spend = bcdiv(strval($query->actual_spend), '100', 2);
            });
        if (count($giftSends) > 0) {
            $count = GiftLogModel::where($where)->count("id");
            return json(["code" => 0, "msg" => "", "data" => $giftSends, "count" => $count]);
        }
        return self::bulidFail("未查询到相关数据");
    }

    /////////////////////////////////////////     赠礼记录      ////////////////////////////////////////----

    public function user_send()
    {
        $uid = Request::param('uid');
        $this->assign('uid', $uid);
        return $this->fetch();
    }

    public function getUserSendList()
    {
        $where            = [];
        $where_time_start = '';
        $where_time_end   = '';

        $uid      = Request::param("uid");
        $anchorid = Request::param("anchorid");
        $liveid   = Request::param('liveid');
        // 时间段类型
        $type       = Request::param('type', 0);
        $start_time = Request::param("start_time");
        $end_time   = Request::param("end_time");

        $page  = Request::param("page");
        $limit = Request::param("limit");

        if ($uid < 1) {
            return self::bulidFail("未查询到相关数据");
        }

        if ($uid) {
            $where["uid"] = $uid;
        }
        if ($anchorid) {
            $where["anchorid"] = $anchorid;
        }
        if ($liveid) {
            $where["liveid"] = $liveid;
        }

        switch ($type) {
            case 1:
                // 今日
                $day_time = date('Y-m-d 00:00:00');
                $end_time = date('Y-m-d 23:59:59');
                break;
            case 2:
                // 昨日
                $day_time = date('Y-m-d 00:00:00', strtotime('-1 day'));
                $end_time = date('Y-m-d 23:59:59', strtotime('-1 day'));
                break;
            case 3:
                // 最近7天
                $day_time = date('Y-m-d 00:00:00', strtotime('-7 days'));
                break;
            case 4:
                // 最近30天
                $day_time = date('Y-m-d 00:00:00', strtotime('-30 days'));
                break;
        }

        if (isset($day_time)) {
            $where_time_start = "create_time > '{$day_time}'";
        }
        if ($start_time) {
            $where_time_start = "create_time > '{$start_time}'";
        }
        if ($end_time) {
            $where_time_end = "create_time < '{$end_time}'";
        }

        $giftSends = GiftLogModel::where($where)->where($where_time_start)->where($where_time_end)
            ->with([
                    'anchor' => function ($query) {
                        $query->field('id, nick_name');
                    },
                    'gift'   => function ($query) {
                        $query->field('id, title');
                    }]
            )->limit(($page - 1) * $limit, $limit)
            ->order("create_time", "desc")
            ->select()->each(function ($query) {
                $query->actual_spend = bcdiv(strval($query->actual_spend), '100', 2);
            });
        if (count($giftSends) > 0) {
            $count = GiftLogModel::where($where)->where($where_time_start)->where($where_time_end)->count("id");
            return json(["code" => 0, "msg" => "", "data" => $giftSends, "count" => $count]);
        }
        return self::bulidFail("未查询到相关数据");
    }
}